package it.polimi.jita.cp.block.scheduler;

import it.polimi.jita.cp.block.InputBuilder;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Iterator;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

public class SchedulerInputBuilder extends InputBuilder<SchedulerInput> {

	@Override
	protected SchedulerInput createInput() throws Exception {
		String filePath = getOptionValue("-i");
		Integer systemFrequency = Integer
				.parseInt((String) getOptionValue("-sf"));

		SchedulerInput input = new SchedulerInput(systemFrequency);

		// TODO Log open file
		System.out.println(String.format("Opening file: %s", filePath));

		URL url = this.getClass().getClassLoader().getResource(filePath);
		InputStream in = url.openStream();
		InputStreamReader isr = new InputStreamReader(in);
		CSVParser csvParser = new CSVParser(isr, CSVFormat.DEFAULT);
		System.out.println(String.format("Reading file: %s", filePath));
		for (Iterator<CSVRecord> iterator = csvParser.iterator(); iterator
				.hasNext();) {
			CSVRecord csvRecord = iterator.next();
			int size = csvRecord.size();
			String name = csvRecord.get(0);
			Double requested = Double.parseDouble(csvRecord.get(1));
			Integer shares = Integer.parseInt(csvRecord.get(2));
			Double reservation = Double.parseDouble(csvRecord.get(3));
			Double limit = size > 4 ? Double.parseDouble(csvRecord.get(4))
					: null;
			VirtualMachine vm = new VirtualMachine(requested, reservation,
					limit, shares);
			vm.setName(name);
			input.add(vm);
		}
		csvParser.close();
		return input;
	}

}
